<template>
  <n-descriptions label-placement="top" bordered :column="3" title="">
    <n-descriptions-item label="物流公司">
      <n-select
        placeholder="请选择物流公司"
        value-field="id"
        label-field="logisticsName"
        :options="logisticsOptions"
        @update:value="handleSelectUpdate"
      />
    </n-descriptions-item>
    <n-descriptions-item label="物流单号">
      <n-input placeholder="请输入物流单号" v-model:value="logisticsSn" />
    </n-descriptions-item>
    <n-descriptions-item label="操作">
      <n-button type="primary" @click="handleShipment">发货</n-button>
    </n-descriptions-item>
  </n-descriptions>
</template>

<script setup lang="ts">
  import { onMounted, ref } from 'vue';
  import { getLogisticsList, orderShipment } from '@/api/order/order';
  import { SelectOption, useMessage } from 'naive-ui';
  import { ResultEnum } from '@/enums/httpEnum';
  interface Props {
    orderId: number; // 订单id
  }
  const props = withDefaults(defineProps<Props>(), {
    orderId: 0,
  });
  interface EmitEvent {
    (e: 'update:shipment'): void;
  }
  const emit = defineEmits<EmitEvent>();

  const message = useMessage();
  const logisticsOptions = ref<SelectOption[]>([]);
  const selectLogisticsId = ref(0);
  const selectLogisticsName = ref('');
  const logisticsSn = ref('');
  function handleSelectUpdate(value: number, options: SelectOption) {
    console.log('handleSelectUpdate', value, options);
    selectLogisticsId.value = value;
    selectLogisticsName.value = options.logisticsName?.toString() || '';
  }

  async function handleShipment() {
    if (props.orderId === 0) {
      message.error('订单ID错误');
      return;
    }
    if (!selectLogisticsId.value) {
      message.error('请选择物流公司');
      return;
    }
    if (!selectLogisticsName.value) {
      message.error('请选择物流公司');
      return;
    }
    if (!logisticsSn.value) {
      message.error('请输入物流单号');
      return;
    }
    const params = {
      orderId: props.orderId,
      logisticsId: selectLogisticsId.value,
      logisticsName: selectLogisticsName.value,
      logisticsSn: logisticsSn.value,
    };
    const { code, message: msg } = await orderShipment(params);

    if (code == ResultEnum.SUCCESS) {
      message.success(msg);
      emit('update:shipment');
    } else {
      message.error(msg);
    }
  }

  onMounted(async () => {
    const response = await getLogisticsList();
    logisticsOptions.value = response;
  });
</script>

<style scoped lang="less"></style>
